package org.xqp.hrm.userdetails;


import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.xqp.hrm.domain.Login;
import org.xqp.hrm.domain.Permission;
import org.xqp.hrm.mapper.PermissionMapper;
import org.xqp.hrm.service.ILoginService;
import org.xqp.hrm.util.AssertUtil;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 提供我们需要的用户信息
 */
@Component
@Slf4j
public class JDBCUserDetailService implements UserDetailsService {

    @Autowired
    private ILoginService loginService;

    @Autowired
    private PermissionMapper permissionMapper ;

    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {

        //查询用户
        Wrapper<Login> wrapper = new EntityWrapper<>();
        wrapper.eq("username", username);
        Login login = loginService.selectOne(wrapper); // 去数据库中根据username查询对应username的Login对象
        AssertUtil.isNotNull(login, "用户不存在");

        //查询用户的权限
        List<GrantedAuthority> authorities = new ArrayList<>();
        List<Permission> permissions = permissionMapper.selectPermissionsByUserId(login.getId()); // 通过UserId去数据库中查找
        if(!permissions.isEmpty()){
            authorities = permissions.stream().map(p -> new SimpleGrantedAuthority(p.getSn()) ).collect(Collectors.toList());
        }

        log.info("加载用户的权限 {}",authorities);

        return new User(login.getUsername(),//用户名
                login.getPassword(),//密码
                login.getEnabled(),login.getAccountNonExpired(),login.getCredentialsNonExpired(),login.getAccountNonLocked(),
                authorities);//权限
    }

}
